package comment

import (
	"errors"
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

type RecordCommentLike struct {
	gorm.Model
	UserId    int64 `gorm:"type:int(11);comment:用户id;"`
	CommentId int64 `gorm:"type:int(11);comment:评论id;"`
}

// 获取点赞记录
func (r *RecordCommentLike) GetCommentLike(userId, commentId int) (*RecordCommentLike, error) {
	return r, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("user_id = ?", userId).Where("comment_id = ?", commentId).First(&r).Error
	})
}

// 评论点赞
func (c *RecordCommentLike) CommentLike(l *RecordCommentLike, num int8) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			m := new(Comment)
			err := tx.Debug().Model(&m).Where("id = ?", l.CommentId).Update("likes", gorm.Expr("likes + ?", num)).Error
			if err != nil {
				return err
			}
			switch num {
			case 1:
				err = tx.Model(&c).Create(&l).Error
				if err != nil {
					return err
				}
			case -1:
				like, err := c.GetCommentLike(int(l.UserId), int(l.CommentId))
				if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
					return err
				}
				err = tx.Model(&c).Unscoped().Delete("id = ?", like.ID).Error
				if err != nil {
					return err
				}
			}
			return nil
		})

	})
}
